package com.kun.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.kun.handler.tenant.DefaultTenantLineHandler;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 如果使用 @TenantScan 注解会覆盖默认的租户忽略扫描包的配置
 *
 * @author kun.li
 */

public class TenantScanRegistrar implements ImportBeanDefinitionRegistrar {


    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        registerTenantScan(importingClassMetadata, registry);
    }

    public void registerTenantScan(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        Map<String, Object> attributes = metadata.getAnnotationAttributes(TenantScan.class.getName());
        Set<String> basePackages = new HashSet<>();
        for (String pkg : (String[]) attributes.get("value")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (String pkg : (String[]) attributes.get("scanBasePackages")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(TenantLineHandler.class);
        beanDefinition.setBeanClassName(DefaultTenantLineHandler.class.getName());
        beanDefinition.setScope(ConfigurableBeanFactory.SCOPE_SINGLETON);
        beanDefinition.getPropertyValues().add("backPackage", basePackages);
        beanDefinition.setInitMethodName("init");
        registry.registerBeanDefinition(DefaultTenantLineHandler.class.getName(), beanDefinition);
    }


}
